<?php

require 'facebook.php';
require 'config.inc.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => $fbconfig['app_id'],
  'secret' => $fbconfig['secret_key'],
  'cookie' => true,
));

$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
  } catch (FacebookApiException $e) {
    echo "Somethings wrong";
  }
}

$uid = $_POST["uid"];
$access_token = $_POST["access_token"];
$grpid= $_POST["grpid"];
$group_name= $_POST["group_name"];
$group_name_encoded = htmlentities($group_name,ENT_QUOTES,'UTF-8');
$link_url= $_POST["link_url"];
$link_url_encoded = htmlentities($link_url,ENT_QUOTES,'UTF-8');
$link_title= $_POST["link_title"];
$link_title_encoded = htmlentities($link_title,ENT_QUOTES,'UTF-8');

$serialize_newtags= $_POST["serialize_newtags"];
$newtags = unserialize($serialize_newtags);

$serialize_oldtags= $_POST["serialize_oldtags"];
$oldtags = unserialize($serialize_oldtags);

$link_desc= $_POST["link_desc"];
$link_desc_encoded = htmlentities($link_desc,ENT_QUOTES,'UTF-8');
$link_pic= $_POST["link_pic"];
$link_pic_encoded = htmlentities($link_pic,ENT_QUOTES,'UTF-8');

//connect to db
$con = mysql_connect("localhost", "vatsav", "2T*vzcd");
if (!$con)
{
  echo 'Could not connect: ' . mysql_error();
  return;
}

$db_selected = mysql_select_db("vatsav", $con);
if (!$db_selected) {
	echo 'Cant use db : ' . mysql_error();
	return;
}

//make the desc small if its big
$link_desc_len = strlen($link_desc);	
$link_desc = substr($link_desc,0,200);
if($link_desc_len != strlen($link_desc))
{
	$link_desc .= "...";
}

//linkid- select distinct max(linkid) from links where uid=1234
$query = "select distinct max(linkid) from links where uid=".$uid;
$result = mysql_query($query);	
// Check result
if (!$result) {
   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
   echo $message;
   //die ($message);
}
else
{
	$row = mysql_fetch_row($result);
	if($row[0] == "NULL")
  		$linkid=1;
	else{
		$linkid=$row[0]+1;
	}
	//echo $linkid;
}
//perfect till here


//commentid - gets facebook comment plugin
$commentid = "linkstar-".$uid."-".$linkid;
//echo $commentid;
//timestamp - some logic below but default for now
//$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
//$phpdate = strtotime( $mysqldate );

//get tags in the ascending order for convenience
$result = mysql_query("select tagid,tag from tags where uid=".$uid." order by tagid");	
// Check result
if (!$result) {
   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
   die($message);
}

$i=0;
$next_tagid=1;
//echo '<br/>'. sizeof($result);
while($row = mysql_fetch_array($result))
{
	$next_tagid=$row[0]+1;
	if(in_array($row[1],$oldtags))
	{
		$tagids[$i] = $row[0];
		$tags[$i] = $row[1];
		$i++;
	}
}

//at this point, we have all the selected old tags' id


//first insert the new group if group_name doesn't exist
$result = mysql_query("select groupid from groups where uid=".$uid." and group_name=\"".$group_name_encoded."\"");	
// Check result
if (!$result) {
   $message  = 'Invalid query: ' . mysql_error() . "<br/>";
   die($message);
}
if(mysql_num_rows($result)==0)
{
	$query = "insert into groups values (".$uid.",\"".$group_name_encoded."\",0,".$grpid.")";
	$result = mysql_query($query);	
	// Check result
	if (!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "<br/>";
		echo $message;
		//die ($message);
	}
}
else{
	$row = mysql_fetch_row($result);
	$grpid = $row[0];
}

//insert the new tags if sizeof($newtags) >0
$len = sizeof($newtags);
//echo '<br/>'.$len.'<br/>';

for($i=0;$i<$len;$i++)
{
	
//	echo $newtags[$i];
	$x=$next_tagid+$i;
	//insert into tags values(10,"awersrf",1234);
	$encoded_newtag = htmlentities($newtags[$i],ENT_QUOTES,'UTF-8');
	$query = "insert into tags values(".$x.",\"".$encoded_newtag."\",".$uid.")";
	$result = mysql_query($query);	

	// Check result
	if (!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "<br/>";
		echo $message;
		//die ($message);
	}
}

//$batchconnection = new mysqli("localhost", "vatsav", "2T*vzcd", "vatsav");
//if ($batchconnection->connect_error) {
//	echo "Error Occurred While Connection To DataBase";
//	//die ("Error Occurred While Connection To DataBase");
//}

//insert the rows in taglink table which explains the tags for a perticular link
$len = sizeof($tagids);
for($i=0;$i<$len;$i++)
{
	//$sqlStatements += "insert into taglink values(".$uid.",".$linkid.",".$tagids[$i].");");
	$query = "insert into taglink values(".$uid.",".$linkid.",".$tagids[$i].")";
	$result = mysql_query($query);	

	// Check result
	if (!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "<br/>";
		echo $message;
		//die ($message);
	}
}

$len = sizeof($newtags);
for($i=0;$i<$len;$i++)
{
	//$sqlStatements += "insert into taglink values(".$uid.",".$linkid.",".$tagids[$i].");");
	$query = "insert into taglink values(".$uid.",".$linkid.",".$next_tagid.")";
	$result = mysql_query($query);	
	$next_tagid++;

	// Check result
	if (!$result) {
		$message  = 'Invalid query: ' . mysql_error() . "<br/>";
		echo $message;
		//die ($message);
	}
}



//finally add the link to links

$query = "insert into links values (".$linkid.",\"".$link_url_encoded."\",CURRENT_TIMESTAMP,".$uid.",".$grpid.",\"".$commentid."\",\"".$link_desc_encoded."\",\"".$link_title_encoded."\",\"".$link_pic_encoded."\")";
//echo $query;

$result = mysql_query($query);	
// Check result
if (!$result) {
	$message  = 'Invalid query: ' . mysql_error() . "<br/>";
	echo $message;
	die ($message);
}
mysql_close($con);

$user = $facebook->api('/'.$uid);
$name = $user["name"];

$group_name_len = strlen($group_name);	
$group_name_new = substr($group_name,0,30);
if($group_name_len != strlen($group_name))
{
	$group_name_new .= "...";
}


?>

<div class="post">
	<div class="post_left">
		<img class="img_src" alt="no image available" src="<?php echo $link_pic; ?>"/><br/>
		<div class="like">
			<a target="_blank" class="likes_url" onclick="javascript:like(<?php echo $uid.','.$linkid; ?>)"> 
				<img src="images/thumbs-up-small.png" alt="like"/>  0 
			</a>
		</div>
	</div>

	<div class="post_right">
		  <div class="post_url"> <a class="post_title" onclick="<?php echo $link_url_encoded; ?>" > <?php echo $link_title; ?> </a> </div> 
		  <div class="post_desc"> <?php echo $link_desc; ?> </div>

		<div class="post_footer"> By 
			<a class="small_link" onclick="javascript:friendProfile(<?php echo $uid;?>)"> 
				<?php echo $name; ?>
			</a> in <a class="small_link" onclick="javascript:group(<?php echo $uid;?>,<?php echo $grpid;?>,'<?php echo $group_name;?>',0,4)"><?php echo $group_name_new;?></a>. 
		</div>
	</div>
</div>

<fb:comments xid='<?php echo "linkstar-$uid-$linkid"; ?>' width='550' publish_feed='false' numposts='4' showform='false' simple='true' reverse='false' > 
</fb:comments>